/*
 * Copyright [2013-2021], Alibaba Group Holding Limited
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.alibaba.polardbx.executor.balancer.stats;

import com.alibaba.polardbx.gms.partition.TablePartRecordInfoContext;
import com.alibaba.polardbx.gms.tablegroup.TableGroupConfig;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Stats of a table-group
 *
 * @author moyi
 * @since 2021/04
 */
public class TableGroupStat {

    private final TableGroupConfig tableGroupConfig;
    private final Map<Long, PartitionGroupStat> pgMap;

    public TableGroupStat(TableGroupConfig tableGroupConfig) {
        this.tableGroupConfig = tableGroupConfig;
        this.pgMap = new HashMap<>();
    }

    public TableGroupConfig getTableGroupConfig() {
        return tableGroupConfig;
    }

    public void addPartition(PartitionStat pstat) {
        long pgId = pstat.getPartitionGroupId();
        PartitionGroupStat pg = this.pgMap.computeIfAbsent(pgId, (x) -> new PartitionGroupStat());
        pg.partitions.add(pstat);
    }

    public List<PartitionStat> getPartitions() {
        return this.pgMap.values().stream()
            .flatMap(x -> x.partitions.stream())
            .collect(Collectors.toList());

    }

    public List<Long> getAllPartitionGroupIds() {
        return new ArrayList<>(this.pgMap.keySet());
    }

    public List<PartitionGroupStat> getPartitionGroups() {
        return new ArrayList<>(this.pgMap.values());
    }

    public List<TablePartRecordInfoContext> getAllTables() {
        return this.tableGroupConfig.getAllTables();
    }


}
